package in.freshstart.java.training.arrays;

public class BinarySearch {
	public static int binarySearch(int[] list, int listLength, int searchItem) {
		int first = 0;
		int last = listLength - 1;
		int mid=0;

		boolean found = false;

		// Loop until found or end of list.
		while (first <= last && !found) {
			// Find the middle.
			mid = (first + last) / 2;

			// Compare the middle item to the search item.
			if (list[mid] == searchItem)
				found = true;
			else { // Not found, readjust search parameters, halving the size &
					// start over.
				if (list[mid] > searchItem)
					last = mid - 1;
				else
					first = mid + 1;
			}
		}

		if (found)
			return mid;
		else
			return (-1);
	}

}
